<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<%@ taglib prefix="his_fns" uri="/WEB-INF/tlds/his_fns.tld" %>
<script type="text/javascript">

    function addRows() {
        var expCode = $('#expCode').val();
        var expName = $('#expName').val();
        var options = $("#storageOut option:selected");  //获取选中的项
        var storageOut = options.val();
        if (expCode == null || expCode == '' || typeof(expCode) == 'undefined' || expName == null || expName == '' || typeof(expName) == 'undefined') {
            toastr.error('没有要添加的数据!');
            return;
        }
        if ($('#quantity').val() == null || $('#quantity').val() == "" || typeof($('#quantity').val()) == "undefined") {
            toastr.error("请输入申请数量!");
            return;
        }
        var quantity = $('#quantity').val();
        var stockQuantity = $('#stockQuantity').val();
        if(new Number(quantity) > new Number(stockQuantity)){
            toastr.error('申请数量不能超过可申请量!');
            return ;
        }
        var tbIdx = 0;
        if (typeof($("#contentTable tbody tr:last").attr('xia')) == 'undefined') {
            tbIdx = 0;
        } else {
            tbIdx = new Number($("#contentTable tbody tr:last").attr('xia')) + 1;
        }

        var list = $("table tr").find("td:eq(0)");
        var jsonuserinfo = $("#inputForm").serializeObject();
        var datastr = JSON.stringify(jsonuserinfo);
        var trHTML = "<tr xia='" + tbIdx + "'>";
        trHTML += "<td hidden>" + datastr + "</td>";
        trHTML += "<td hidden><input id='infoId" + tbIdx + "' name='expProvideApplicationList[" + tbIdx + "].infoId' value='" + $('#infoId').val() + "'/></td>";
        trHTML += "<td hidden>" + storageOut + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].storageOut' value='" + storageOut + "'/></td>";
        trHTML += "<td>" + expCode + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].expCode' value='" + expCode + "'/></td>";
        trHTML += "<td>" + expName + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].expName' value='" + expName + "'/></td>";
        trHTML += "<td hidden>" + $('#minSpec').val() + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].minSpec' value='" + $('#minSpec').val() + "'/></td>";
        trHTML += "<td hidden>" + $('#minUnits').val() + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].minUnits' value='" + $('#minUnits').val() + "'/></td>";
        trHTML += "<td hidden>" + $("#minUnitsName").find("option:selected").text() + "</td>";
        trHTML += "<td hidden>" + $('#packageNum').val() + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].packageNum' value='" + $('#packageNum').val() + "'/></td>";
        trHTML += "<td>" + $('#packageSpec').val() + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].packageSpec' value='" + $('#packageSpec').val() + "'/></td>";
        trHTML += "<td hidden>" + $('#packageUnits').val() + "<input type='hidden' name='expProvideApplicationList[" + tbIdx + "].packageUnits' value='" + $('#packageUnits').val() + "'/></td>";
        trHTML += "<td>" + $("#packageUnitsName").find("option:selected").text() + "</td>";
        trHTML += "<td hidden>" + $('#supplierId').val() + "</td>";
        trHTML += "<td>" + $("#supplierName").find("option:selected").text() + "</td>";
        trHTML += "<td ><input class='form-control' name='expProvideApplicationList[" + tbIdx + "].quantity' value='" + $('#quantity').val() + "'/></td>";
        trHTML += "<td><a href='#' onclick='removeList(this)' class='applyBt btn btn-danger btn-xs'>删除</a></td>"
        trHTML += "</tr>";
        $("#inputForm input").val("");
        $("#contentTable").append(trHTML);
        return loadDiv('rigthCenterDiv', '${ctx}/csm/expProvideApplication/form');
    }
    //表单自动回填的方法
    var fillForm = function ($form, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        for (var key in jsonObj) { // 遍历json字符串
            var objtype = jsonObjType(jsonObj[key]); // 获取值类型
            if (objtype === "array") { // 如果是数组，一般都是数据库中多对多关系
                var obj1 = jsonObj[key];
                for (var arraykey in obj1) {
                    // alert(arraykey + jsonObj[arraykey]);
                    var arrayobj = obj1[arraykey];
                    for (var smallkey in arrayobj) {
                        setCkb(key, arrayobj[smallkey]);
                        break;
                    }
                }
            } else if (objtype === "object") { // 如果是对象，啥都不错，大多数情况下，会有 xxxId
                // 这样的字段作为外键表的id

            } else if (objtype === "string") { // 如果是字符串
                var str = jsonObj[key];
                var date = new Date(str);
                if (date.getDay()) { // 这种判断日期是本人懒，不想写代码了，大家慎用。
                    $("[name=" + key + "]", $form).val(str);
                    continue;
                }

                var tagobjs = $("[name=" + key + "]", $form);
                if ($(tagobjs[0]).attr("type") == "radio") {// 如果是radio控件
                    $.each(tagobjs, function (keyobj, value) {
                        if ($(value).attr("val") == jsonObj[key]) {
                            value.checked = true;
                        }
                    });
                    continue;
                }
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            } else { // 其他的直接赋值
                $("[name=" + key + "]", $form).val(jsonObj[key]);
            }

        }
    }

    var setCkb = function (name, value) {
        // alert(name + " " + value);
        // $("[name=" + name + "][value=" + value + "]").attr("checked", "checked");
        // 不知为何找不到具体标签;
        $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
    }

    var fillckb = function (name, json) {
        var jsonObj = json;
        if (typeof json === 'string') {
            jsonObj = $.parseJSON(json);
        }
        var str = jsonObj[name];
        if (typeof str === "string") {
            var array = str.split(",");
            $.each(array, function (key, value) {
                setCkb(name, value);
            });
        }
    }

    var jsonObjType = function (obj) {
        if (typeof obj === "object") {
            var teststr = JSON.stringify(obj);
            if (teststr[0] == '{' && teststr[teststr.length - 1] == '}')
                return "class";
            if (teststr[0] == '[' && teststr[teststr.length - 1] == ']')
                return "array";
        }
        return typeof obj;
    }
</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li class="active">
                <a href="#" onclick="loadDiv('rigthCenterDiv','${ctx}/csm/expProvideApplication/form')">添加</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12">
                    <form:form id="inputForm" data-parsley-validate="" modelAttribute="expProvideApplication" class="form-horizontal">
                        <form:hidden path="infoId" id="infoId"/>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">编码：</label>
                            <div class="col-sm-6">
                                <form:input path="expCode" id="expCode" htmlEscape="false" class="form-control"  maxlength="32" readonly="true"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">名称：</label>
                            <div class="col-sm-6">
                                <form:input path="expName" id="expName" htmlEscape="false" class="form-control" maxlength="100" />
                            </div>
                        </div>
                        <div class="form-group" hidden="hidden">
                            <label class="col-sm-4 control-label">规格：</label>
                            <div class="col-sm-6">
                                <form:input path="minSpec" id="minSpec" htmlEscape="false" class="form-control" maxlength="20" readonly="true"/>
                            </div>
                        </div>
                        <div class="form-group" hidden="hidden">
                            <label class="col-sm-4 control-label">单位：</label>
                            <div class="col-sm-6">
                                <input type="hidden" id="minUnits" />
                                <form:select path="minUnits" id="minUnitsName" htmlEscape="false" class="form-control" data-parsley-required="true" disabled="true">
                                    <form:option value=""></form:option>
                                    <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group" hidden="hidden">
                            <label class="col-sm-4 control-label">包装数：</label>
                            <div class="col-sm-6">
                                <form:input path="packageNum" id="packageNum" htmlEscape="false" class="form-control"  maxlength="8" readonly="true"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">规格：</label>
                            <div class="col-sm-6">
                                <form:input path="packageSpec" id="packageSpec" htmlEscape="false" class="form-control"  maxlength="20" readonly="true"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">单位：</label>
                            <div class="col-sm-6">
                                <input type="hidden" id="packageUnits" />
                                <form:select path="packageUnits" id="packageUnitsName" htmlEscape="false" class="form-control" data-parsley-required="true" disabled="true">
                                    <form:option value=""></form:option>
                                    <form:options items="${fns:getDictList('SPEC_UNIT')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">生产厂商：</label>
                            <div class="col-sm-6">
                                <input type="hidden" id="supplierId" />
                                <form:select path="expStock.expSupplierCata.id" id="supplierName" class="form-control" data-parsley-required="true" disabled="true">
                                    <form:option value="" label="" />
                                    <form:options items="${his_fns:getExpSupplierList()}" itemLabel="supplierJc" itemValue="id" htmlEscape="false" />
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">申请数量：</label>
                            <div class="col-sm-6">
                                <form:input path="quantity" id="quantity" htmlEscape="false" class="form-control"  maxlength="8" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label">可申请数量：</label>
                            <div class="col-sm-6">
                                <form:input path="" id="stockQuantity" htmlEscape="false" class="form-control" maxlength="8" disabled="true"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <input id="btnSubmit" class="btn btn-primary" type="button" value="确 定" onclick="addRows()">&nbsp;
                                <input id="btnCancel" class="btn" type="button" value="关 闭" onclick="closeRight()">
                            </div>
                        </div>
                    </form:form>
                </div>
            </div>
        </section>
    </div>
</div>
<script type="text/javascript">
    var storageId = $('#storageOut').val();  //供货单位
    /*消耗品自动补全*/
    autoCompleteExpPrice("expName");
    function autoCompleteExpPrice(inputId) {
        var list = $("table tr").find("td:eq(0)");  //左侧table表格数据
        var dataList = [];
        if (list.length > 0) {
            for (var i = 0; i < list.length; i++) {
                var data = jQuery.parseJSON(list[i].innerText);
                dataList.push(data);
            }
        }

        var url = "${ctx}/csm/expStock/autoCompleteStock?storageId=" + storageId;
        autoComplete(inputId, url,
                function (data) {
                    var rows = [];
                    for (var i = 0; i < data.length; i++) {
                        rows[rows.length] = {
                            data: data[i],
                            value: data[i].expCode,
                            result: data[i].expName
                        };
                    }
                    return rows;
                }, function (data, i, max) {
                    return data.expName + " || " + data.packageSpec + " || " + data.expSupplierCata.supplierJc;
                }, function (event, data, formatted) {
                    if (dataList != null && dataList != [] && typeof(dataList) != 'undefined' && dataList.length > 0) {
                        for (var i = 0; i < dataList.length; i++) {
                            if (dataList[i].infoId == data.infoId) {
                                toastr.error('列表中该规格的消耗品已经存在,请重新选择!');
                                addExpList();
                                return;
                            }
                        }
                    }
                    $('#infoId').attr('value', data.infoId);
                    $('#expCode').attr('value', data.expCode);
                    $('#expName').attr('value', data.expName);
                    $('#packageSpec').attr('value', data.packageSpec);
                    $('#packageUnits').val(data.packageUnits);
                    $('#packageUnitsName').val(data.packageUnits).trigger("change");
                    $('#minSpec').attr('value', data.minSpec);
                    $('#minUnits').val(data.minUnits);
                    $('#minUnitsName').val(data.minUnits).trigger("change");
                    $('#packageNum').attr('value', data.packageNum);
                    $('#supplierId').attr('value', data.expSupplierCata.id);
                    $("#supplierName option[value='" + data.expSupplierCata.id + "']").attr("selected", true);
                    $('#supplierName').change();
                    $('#stockQuantity').attr('value',data.quantity);
                })
    }
    //关闭右侧添加消耗品明细页面
    function closeRight() {
        $("#applicationRightDiv").attr("style", "display: none");
        $("#applicationLeftDiv").attr("class", "main-content col-lg-12");
        $("#applicationLeftDiv").show('normal');
        var list = $("table tr").find("td:eq(0)");  //左侧table表格数据
        if(list.length == 0){
            document.getElementById('storageOut').disabled = false;
        }else{
            document.getElementById('storageOut').disabled = true;
        }
    }
</script>